package com.example.research.controller;

import com.example.research.model.Teacher;
import com.example.research.service.DepartmentService;
import com.example.research.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/teachers")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public String listTeachers(Model model) {
        model.addAttribute("teachers", teacherService.findAll());
        return "teachers/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("teacher", new Teacher());
        model.addAttribute("departments", departmentService.findAll());
        return "teachers/add";
    }

    @PostMapping("/add")
    public String addTeacher(@ModelAttribute Teacher teacher) {
        teacherService.save(teacher);
        return "redirect:/teachers";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Integer id, Model model) {
        model.addAttribute("teacher", teacherService.findById(id));
        model.addAttribute("departments", departmentService.findAll());
        return "teachers/edit";
    }

    @PostMapping("/edit/{id}")
    public String updateTeacher(@PathVariable Integer id, @ModelAttribute Teacher teacher) {
        teacher.setTeacherId(id);
        teacherService.save(teacher);
        return "redirect:/teachers";
    }

    @GetMapping("/delete/{id}")
    public String deleteTeacher(@PathVariable Integer id) {
        teacherService.delete(id);
        return "redirect:/teachers";
    }
}